package com.leslie.hhcommunity.service.impl;

import com.leslie.hhcommunity.service.LikeService;
import com.leslie.hhcommunity.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.service.impl
 * @ClassnName:LikeServiceImpl
 * @Description:
 * @Date 2022/1/5  16:50
 */
@Service
public class LikeServiceImpl implements LikeService {

	@Autowired
	RedisTemplate redisTemplate;

	/**
	 * 点赞
	 *
	 * @param userId
	 * @param entityType
	 * @param entityId
	 */
	@Override
	public void like(int userId, int entityType, int entityId, int entityUserId) {

		redisTemplate.execute(new SessionCallback() {
			@Override
			public Object execute(RedisOperations operations) throws DataAccessException {

				String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
				String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);

				//看某人是否点过赞, 在事务外查询
				Boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);

				//开启事务
				operations.multi();
				if (isMember){
					redisTemplate.opsForSet().remove(entityLikeKey,userId);
					operations.opsForValue().decrement(userLikeKey);
				}else {
					redisTemplate.opsForSet().add(entityLikeKey,userId);
					operations.opsForValue().increment(userLikeKey);
				}
				//关闭事务
				return operations.exec();
			}
		});
	}

	/**
	 * 查询某个实体点赞的数量
	 *
	 * @param entityType
	 * @param entityId
	 * @return
	 */
	@Override
	public long findEntityLikeCount(int entityType, int entityId) {
		String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
		return redisTemplate.opsForSet().size(entityLikeKey);
	}

	/**
	 * 查询某人对某个实体点赞的状态
	 * 1表示已赞
	 * @param userId
	 * @param entityType
	 * @param entityId
	 * @return
	 */
	@Override
	public int findEntityLikeStatus(int userId, int entityType, int entityId) {
		String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
		return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
	}

	/**
	 * 查询某个用户获得的赞
	 * @param userId
	 * @return
	 */
	@Override
	public int findUserLikeCount(int userId){
		String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
		Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
		return count == null ? 0 : count;
	}

}
